package com.dms.modules.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.service.MerchantService;
import com.dms.modules.order.dto.RefundAuditDTO;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.order.vo.OrderDetailVO;
import com.dms.modules.order.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/api/v1/merchant/orders")
@Api(tags = "商家订单管理")
@RequiredArgsConstructor
@PreAuthorize("hasRole('MERCHANT')")
public class MerchantOrderController {

    private final OrderService orderService;
    private final MerchantService merchantService;

    /**
     * 获取当前商家信息
     * @return 商家实体
     * @throws BusinessException 如果未找到商家信息或商家状态异常
     */
    private Merchant getCurrentMerchant() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("未获取到用户信息");
        }

        Merchant merchant = merchantService.lambdaQuery()
                .eq(Merchant::getUserId, userId)
                .eq(Merchant::getStatus, 1)  // 确保商家状态正常
                .one();
                
        if (merchant == null) {
            throw new BusinessException("未找到对应的商家信息");
        }

        return merchant;
    }

    @GetMapping("/list")
    @ApiOperation("获取商家订单列表")
    public ApiResponse<IPage<OrderVO>> getMerchantOrders(
            @ApiParam("页码") @RequestParam(defaultValue = "1") @Min(1) Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") @Min(1) Integer pageSize,
            @ApiParam("订单状态：0-待支付，1-已支付，2-已发货，3-已完成，4-已取消，5-退款中，6-已退款") 
            @RequestParam(required = false) Integer status) {
        try {
            Merchant merchant = getCurrentMerchant();
            Page<Order> page = new Page<>(pageNum, pageSize);
            IPage<OrderVO> orderVOPage = orderService.getMerchantOrders(page, merchant.getId(), status);
            return ApiResponse.success(orderVOPage);
        } catch (BusinessException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @ApiOperation("获取订单详情")
    public ApiResponse<OrderDetailVO> getOrderDetail(@PathVariable @NotNull Long id) {
        try {
            Merchant merchant = getCurrentMerchant();
            OrderDetailVO orderDetailVO = orderService.getMerchantOrderDetail(merchant.getId(), id);
            return ApiResponse.success(orderDetailVO);
        } catch (BusinessException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/{id}/ship")
    @ApiOperation("发货")
    public ApiResponse<Boolean> shipOrder(
            @PathVariable @NotNull Long id,
            @RequestParam @NotNull String deliveryCompany,
            @RequestParam @NotNull String deliveryNo) {
        try {
            Merchant merchant = getCurrentMerchant();
            boolean result = orderService.shipOrder(id, deliveryCompany, deliveryNo);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/refund/audit")
    @ApiOperation("审核退款申请")
    public ApiResponse<Boolean> auditRefund(@RequestBody @Valid RefundAuditDTO refundAuditDTO) {
        try {
            Merchant merchant = getCurrentMerchant();
            boolean result = orderService.auditRefund(merchant.getId(), refundAuditDTO);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
} 